package com.bjpowernode.boss.web.interceptors;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.bjpowernode.boss.common.cilent.RedisClient;
import com.bjpowernode.boss.common.constants.KeyConstants;
import com.bjpowernode.boss.common.enums.AjaxCode;
import com.bjpowernode.boss.common.error.BossException;
import com.bjpowernode.boss.web.models.result.AjaxResult;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    private RedisClient redisClient;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }
        String authorization = request.getHeader("Authorization");
        String operatorId = request.getHeader("operatorId");
        if(StrUtil.isNotBlank(authorization)&&authorization.startsWith("Bearer")&&StrUtil.isNotBlank(operatorId)){
            String jwt = authorization.substring(7);
            if(StrUtil.isNotBlank(jwt)){
                String key = KeyConstants.OPERATOR_LOGIN_JWT + operatorId;
                String jwtInRedis = redisClient.getFieldValue(key, "jwt");
                if(jwt.equals(jwtInRedis)){
                    return true;
                }
            }
        }
        try {
            AjaxResult ajaxResult = new AjaxResult(AjaxCode.LOGIN_TOKEN_INVALID,"");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out =  response.getWriter();
            out.print(JSONUtil.toJsonStr(ajaxResult));
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BossException(AjaxCode.LOGIN_TOKEN_INVALID);
        }
        return false;
    }
}
